package com.yaowk.sfp.system.server.service.impl;

import com.yaowk.sfp.system.api.model.Role;
import com.yaowk.sfp.system.server.dao.MenuDao;
import com.yaowk.sfp.system.server.dao.UserDao;
import com.yaowk.sfp.system.server.entity.SysMenu;
import com.yaowk.sfp.system.server.entity.SysRole;
import com.yaowk.sfp.system.server.entity.SysUser;
import com.yaowk.sfp.system.server.service.base.RoleServiceBase;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class RoleServiceImpl extends RoleServiceBase {

    @Autowired
    private UserDao userDao;
    @Autowired
    private MenuDao menuDao;

    @Override
    @Transactional
    public void menuEdit(Long roleId, List<Long> menuId) {
        SysRole sysRole = getDao().findOne(roleId);
        Set<SysMenu> sysMenus = new HashSet<>();
        sysRole.setMenus(sysMenus);
        if (CollectionUtils.isNotEmpty(menuId)) {
            for (Long id : menuId) {
                sysMenus.add(menuDao.findOne(id));
            }
        }
        getDao().save(sysRole);
    }

    @Override
    public List<Role> findRolesByUserId(Long userId) {
        SysUser sysUser = userDao.findOne(userId);
        return entity2Model(sysUser.getRoles());
    }

    @Override
    public List<Role> findAllByUserId(Long userId) {
        SysUser sysUser = userDao.findOne(userId);
        return entity2Model(sysUser.getRoles());
    }
}